import pickle
import base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """
    登录后合并购物车【从cookie覆盖redis
    :param request: 本次登录成功以后的请求对象，获取cookie
    :param user: 用户
    :param response:响应对象，用于设置 cookie
    :return: 响应对象  因为在函数内部操作了cookie需要返回给客户端
    """
    cookie_cart = request.COOKIES.get('cart')
    # 如果cookie没有购物车商品信息，就不用合并了
    if cookie_cart is None:
        return response

    # 解析cookie购物车数据
    cookie_cart = pickle.loads(base64.b64decode(cookie_cart.encode()))
    redis_conn = get_redis_connection('cart')
    pl = redis_conn.pipeline()
    # 直接遍历cookie中的购物车， 把同样sku_id的数据设置到redis
    for sku_id, sku_dict in cookie_cart.items():
        # 1. 先覆盖cart_<user_id>对应的sku商品信息
        pl.hset('cart_%s' % user.id, sku_id, int(sku_dict['count']))
        if sku_dict['selected']:
            pl.sadd("cart_selected_%s" % user.id, sku_id)
        else:
            pl.srem('cart_selected_%s' % user.id, sku_id)
        pl.execute()

        # 遍历覆盖完成以后，直接删除cookie
        response.delete_cookie('cart')

        return response
